package com.zjl.core.shiro.realm;

import com.zjl.common.enums.LockStatus;
import com.zjl.core.entity.BaseUserWithBLOBs;
import com.zjl.core.service.BaseUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author : zhangjl
 * @Description :
 * @Created : 2018-05-29 16:15
 **/
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private BaseUserService baseUserService;
    /**
     * 实现用户的授权逻辑
     *
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        return null;
    }

    /**
     * 实现用户登录时的认证逻辑
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String account = (String) token.getPrincipal();
        BaseUserWithBLOBs user = baseUserService.getUserByAccount(account);
        if (user == null){
            //没找到帐号
            throw new UnknownAccountException();
        }

        if (LockStatus.LOCK.getFlag().equals(user.getIsLock())){
            //帐号锁定
            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(account, user.getPassword(), this.getName());
        return simpleAuthenticationInfo;
    }
}
